import debounce from '@/utils/debounce';
import processString from '@/utils/processString';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  DrawerForm,
  ProForm,
  ProFormDateTimePicker,
  ProFormDigit,
  ProFormList,
  ProFormSegmented,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import React, { useCallback, useRef, useState } from 'react';
import { getStoreCate, getStoreDetail } from '../service';
export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<any>;

export type CreateUserProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<any>;
  formType: number;
};
const cpsConf = [
  {
    label: 'APP_TEST',
    value: 'CPS-ZBJ-yf',
  },
  {
    label: 'APP',
    value: 'CPS-ZBJ-yf2',
  },
  {
    label: 'APP_3',
    value: 'CPS-ZBJ-yf3',
  },
  {
    label: 'APP_4',
    value: 'CPS-ZBJ-yf4',
  },
  {
    label: 'APP_5',
    value: 'CPS-ZBJ-yf5',
  },
  {
    label: 'APP_6',
    value: 'CPS-ZBJ-yf6',
  },
  {
    label: 'APP_7',
    value: 'CPS-ZBJ-yf7',
  },
];
// eslint-disable-next-line react-hooks/rules-of-hooks
const CommandDrawer: React.FC<CreateUserProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [editType, setEditType] = useState(0);
  const [opType, setOpType] = useState('edit');

  const requestAPI = useCallback(
    debounce(async (shopName: string, type: any) => {
      if (!shopName) return;
      const rsp = await getStoreDetail({ shopName });
      if (rsp.code === 'SUCCESS') {
        if (!!rsp.data?.name) {
          if (type === 1) {
            formRef?.current?.setFieldsValue({
              cate: rsp.data.cate,
              productName: rsp.data.dname,
            });
          } else {
            formRef?.current?.setFieldsValue({
              cate: rsp.data.cate,
            });
          }
        }
      }
    }, 500), // 500ms 无新输入再请求
    [],
  );
  return (
    <DrawerForm
      title={props.formType === 0 ? '创建口令' : '编辑口令'}
      width="820px"
      formRef={formRef}
      visible={props.updateModalVisible}
      onVisibleChange={(val) => {
        if (!val) {
          props.onCancel();
        }
        setEditType(props?.formType);
        if (props?.formType === 1) {
          setOpType('edit');
          formRef?.current?.setFieldsValue({
            opType: 'edit',
            rate: props?.values.rate / 100,
            qualityRate: (props?.values.rate * 84.5) / 10000,
            subRate: props?.values.subRate / 100,
            status: props?.values.status,
            productName: props?.values.productName,
            cate: props?.values.cate,
          });
          let name = processString(props?.values.shopName).slice(0, 2);
          if (props?.values.commandType === 2) {
            name = props?.values.productName;
          }
          requestAPI(name, 1);
        } else {
          formRef?.current?.setFieldsValue({
            qualityRate: '',
            subRate: '',
            rate: '',
            shopName: '',
            productName: '',
            cate: '',
            status: 1,
          });
        }
      }}
      onFinish={async (val) => {
        let data = val;

        if (props.formType === 1 && opType === 'edit') {
          data = { ...data, id: props?.values.id, shopName: props?.values.shopName };
        }
        props.onSubmit({ ...data, status: ~~data.status });
      }}
    >
      {props?.formType === 1 ? (
        <ProFormSegmented
          name="opType"
          // label="选择跟单方式"
          onChange={(val: any) => {
            setOpType(val);
            setEditType(~~!editType);
            if (val === 'create') {
              formRef?.current?.setFieldsValue({
                qualityRate: (props?.values.rate * 84.5) / 10000,
                subRate: props?.values.subRate / 100,
                rate: props?.values.rate / 100,
                shopName: props?.values.shopName,
                productName: props?.values.productName,
                cate: props?.values.cate,
              });
              let name = processString(props?.values.shopName).slice(0, 2);
              if (props?.values.commandType === 2) {
                name = props?.values.productName;
              }
              requestAPI(name, 1);
            }
          }}
          valueEnum={{
            edit: '编辑',
            create: '新建',
          }}
        />
      ) : (
        ''
      )}
      <ProFormSwitch
        checkedChildren="立即使用"
        unCheckedChildren="停止使用"
        label="状态"
        name="status"
      />
      {editType === 0 ? (
        <>
          <ProForm.Group>
            <ProFormText
              width="md"
              name="shopName"
              label="直播间信息"
              tooltip="最长为 64 位"
              placeholder="请输入店铺信息"
              rules={[{ required: true, message: '店铺信息不能为空!' }]}
            />
            <ProFormText
              width="md"
              name="productName"
              label="商品名称"
              placeholder="请输入商品名称"
              fieldProps={{
                // 通过 fieldProps 透传 Input 属性
                onChange: async (e) => {
                  requestAPI(e.target.value);
                },
              }}
              rules={[{ required: true, message: '商品名称不能为空!' }]}
            />
          </ProForm.Group>

          <ProForm.Group>
            <ProFormDigit
              width="sm"
              label="后台比例"
              name="rate"
              placeholder="请输入后台佣金"
              min={1}
              fieldProps={{ precision: 2 }}
              onChange={async (val) => {
                formRef?.current?.setFieldsValue({
                  subRate: Math.round((val * 78) / 100),
                  proRate: Math.round((val * 80) / 100),
                  qualityRate: (val * 84.5) / 100,
                });
              }}
              rules={[{ required: true, message: '后台佣金不能为空!' }]}
            />
            <ProFormSelect
              name="cate"
              label="选择分类"
              width="sm"
              request={async () => {
                const rsp = await getStoreCate();
                return rsp.data;
              }}
              placeholder="请输入产品渠道"
              rules={[{ required: true, message: '产品渠道不能为空!' }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormDigit
              width="sm"
              label="散单佣金"
              name="subRate"
              placeholder="请输入散单佣金"
              fieldProps={{ precision: 0 }}
              tooltip="渠道佣金不填，默认80%处理"
            />
            <ProFormDigit
              width="sm"
              label="保量佣金"
              name="qualityRate"
              placeholder="请输入保量佣金"
              fieldProps={{ precision: 2 }}
              // rules={[{ required: true, message: '保量佣金不能为空!' }]}
            />
          </ProForm.Group>
          <ProFormList
            name="cps"
            creatorButtonProps={{
              position: 'bottom',
              creatorButtonText: '添加口令',
            }}
          >
            <ProForm.Group>
              <ProFormSelect
                name="extData"
                label="口令渠道"
                width="sm"
                request={async () => cpsConf}
                placeholder="请输入产品渠道"
                rules={[{ required: true, message: '产品渠道不能为空!' }]}
              />
              <ProFormDateTimePicker
                name="time"
                label="口令开始时间"
                tooltip="口令开始时间如果不选，默认为创建时间"
              />
            </ProForm.Group>
            <ProFormTextArea
              name="wxCommand"
              label="小程序链接"
              placeholder="请输入微信口令"
              rules={[{ required: true, message: '微信口令不能为空!' }]}
            />
            {/* <ProFormTextArea
          name="command"
          label="抖音口令"
          placeholder="请输入抖音口令"
          // rules={[{ required: true, message: '抖音口令不能为空!' }]}
        /> */}
          </ProFormList>
        </>
      ) : (
        <>
          <ProFormText
            width="md"
            name="productName"
            label="商品名称"
            placeholder="请输入商品名称"
            fieldProps={{
              // 通过 fieldProps 透传 Input 属性
              onChange: async (e) => {
                requestAPI(e.target.value);
              },
            }}
            rules={[{ required: true, message: '商品名称不能为空!' }]}
          />
          <ProForm.Group>
            <ProFormDigit
              width="sm"
              label="后台比例"
              name="rate"
              disabled
              placeholder="请输入后台佣金"
              min={1}
              fieldProps={{ precision: 2 }}
            />
            <ProFormSelect
              name="cate"
              label="选择分类"
              width="sm"
              request={async () => {
                const rsp = await getStoreCate();
                return rsp.data;
              }}
              placeholder="请输入产品渠道"
              rules={[{ required: true, message: '产品渠道不能为空!' }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormDigit
              width="sm"
              label="散单佣金"
              name="subRate"
              fieldProps={{ precision: 0 }}
              tooltip="渠道佣金不填，默认80%处理"
            />
            <ProFormDigit
              width="sm"
              label="保量佣金"
              name="qualityRate"
              placeholder="请输入保量佣金"
              fieldProps={{ precision: 2 }}
            />
          </ProForm.Group>
        </>
      )}
    </DrawerForm>
  );
};

export default CommandDrawer;
